package com.wang.config.security;

import com.wang.base.http.SystemCode;
import com.wang.base.util.RedisUtil;
import com.wang.base.util.RedisUtil;
import com.wang.base.util.RestUtil;
import com.wang.base.util.TokenUtil;
import com.wang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author JoyBoy
 */
@Component
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    private final ThreadPoolTaskExecutor authApplicationExecutor;
    private final RedisUtil redisUtil;
    private static final String USER_TOKEN = "td:user:token::";

    private static final Map<String, Object> MAP;
    static {
        MAP = new ConcurrentHashMap<>(1);
    }

    @Autowired
    public RestAuthenticationSuccessHandler(ThreadPoolTaskExecutor authApplicationExecutor, RedisUtil redisUtil) {
        this.authApplicationExecutor = authApplicationExecutor;
        this.redisUtil = redisUtil;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        Object object = authentication.getPrincipal();
        if (object != null){
            User springUser = (User) object;
            com.wang.domain.User user = userService.getUserByUserName(springUser.getUsername());
            if (user != null){
                String token = TokenUtil.createToken(springUser.getUsername());
                // 异步将token放入redis存放
                CompletableFuture<Void> setTokenOnRedis = CompletableFuture.runAsync(() ->
                        redisUtil.set(USER_TOKEN+user.getUserName(), token, 2, TimeUnit.HOURS), authApplicationExecutor);
                MAP.put("token", token);
                MAP.put("role",user.getRole().getName());
                CompletableFuture.allOf(setTokenOnRedis);
                RestUtil.response(response, SystemCode.OK.getCode(), SystemCode.OK.getMessage(), MAP);
            }
        } else {
            RestUtil.response(response, SystemCode.UNAUTHORIZED.getCode(), SystemCode.UNAUTHORIZED.getMessage());
        }
    }
}
